import { h } from 'vue'
import { ElTag, ElImage, ElButton, ElIcon, ElSwitch } from 'element-plus'
import { ArrowUp, ArrowDown, ZoomIn } from '@element-plus/icons-vue'

/**
 * 搜索配置
 */
export const searchConfig = [
  {
    field: 'title',
    label: '文章标题',
    component: 'Input',
    placeholder: '请输入文章标题',
    defaultValue: '',
    showInMore: false,
  },
  {
    field: 'categoryId',
    label: '分类',
    component: 'Select',
    placeholder: '请选择分类',
    defaultValue: '',
    showInMore: false,
    options: [],
  },
  {
    field: 'type',
    label: '类型',
    component: 'Select',
    placeholder: '请选择类型',
    defaultValue: '',
    showInMore: false,
    options: [
      { label: '公开', value: '1' },
      { label: '私密', value: '2' },
      { label: '加密', value: '3' },
    ],
  },
  {
    field: 'status',
    label: '状态',
    component: 'Select',
    placeholder: '请选择状态',
    defaultValue: '',
    showInMore: false,
    options: [
      { label: '已发布', value: '1' },
      { label: '草稿', value: '0' },
    ],
  },
  {
    field: 'dateRange',
    label: '创建时间',
    component: 'DateRangePicker',
    defaultValue: [],
    showInMore: false,
    props: {
      startPlaceholder: '开始日期',
      endPlaceholder: '结束日期',
      valueFormat: 'YYYY-MM-DD',
    },
  },
]

// 分类标签颜色池
const CATEGORY_COLORS = [
  '#409EFF', // 蓝
  '#67C23A', // 绿
  '#E6A23C', // 橙
  '#F56C6C', // 红
  '#909399', // 灰
  '#8D4EDA', // 紫
  '#00B8A9', // 青
]

function getCategoryColor(id) {
  if (!id) return CATEGORY_COLORS[0]
  // 简单hash: 字符串转charCode累加
  let hash = 0
  for (let i = 0; i < String(id).length; i++) {
    hash += String(id).charCodeAt(i)
  }
  return CATEGORY_COLORS[hash % CATEGORY_COLORS.length]
}

/**
 * 表格列配置
 */
export const createTableConfig = (router, handlers) => [
  {
    type: 'selection',
    width: 55,
    fixed: 'left',
  },
  {
    type: 'index',
    label: '序号',
    width: 60,
    align: 'center',
  },
  {
    prop: 'picUrl',
    label: '封面',
    width: 100,
    align: 'center',
    render: (row) => {
      if (!row.picUrl) {
        return h('div', { class: 'no-cover' }, '暂无封面')
      }

      return h(
        'div',
        {
          class: 'cover-column',
        },
        [
          h(ElImage, {
            src: row.picUrl,
            previewSrcList: [row.picUrl],
            class: 'article-cover',
            fit: 'cover',
            lazy: true,
            zIndex: 3000,
            initialIndex: 0,
            appendToBody: true,
            previewTeleported: true,
            hideOnClickModal: false,
          }),
        ],
      )
    },
  },
  {
    prop: 'title',
    label: '标题',
    minWidth: 300,
    showOverflowTooltip: true,
    render: (row) => {
      return h(
        'div',
        {
          class: 'article-title',
          onClick: () => {
            router.push({
              path: '/article/edit',
              query: { id: row.id },
            })
          },
          style: {
            cursor: 'pointer',
          },
        },
        row.title,
      )
    },
  },
  {
    prop: 'category',
    label: '分类',
    width: 100,
    render: (row) => {
      const color = getCategoryColor(row.category?.id)
      return h(
        ElTag,
        {
          effect: 'light',
          style: { borderRadius: '4px', backgroundColor: color, color: '#fff', border: 'none' },
        },
        () => row.category?.name || '-',
      )
    },
  },
  {
    prop: 'author',
    label: '作者',
    width: 120,
    render: (row) => row.author?.nickname || '-',
  },
  {
    prop: 'type',
    label: '类型',
    width: 100,
    render: (row) => {
      const typeMap = {
        1: { label: '公开', type: 'success' },
        2: { label: '私密', type: 'warning' },
        3: { label: '加密', type: 'danger' },
      }
      const config = typeMap[row.type] || { label: '未知', type: 'info' }
      return h(
        ElTag,
        {
          type: config.type,
          effect: 'light',
          style: { borderRadius: '4px' },
        },
        () => config.label,
      )
    },
  },
  {
    prop: 'status',
    label: '状态',
    width: 100,
    render: (row) => {
      return h(
        ElTag,
        {
          type: row.status === '1' ? 'success' : 'info',
          effect: 'light',
          style: { borderRadius: '4px' },
        },
        () => (row.status === '1' ? '已发布' : '草稿'),
      )
    },
  },
  {
    prop: 'isRecommend',
    label: '推荐',
    width: 100,
    align: 'center',
    render: (row) => {
      return h(ElSwitch, {
        modelValue: row.isRecommend === '1',
        disabled: row.recommendDisabled,
        'onUpdate:modelValue': (value) => {
          row.onToggleRecommend?.(row, value)
        },
        activeColor: '#13ce66',
        inactiveColor: '#dcdfe6',
      })
    },
  },
  {
    prop: 'createOn',
    label: '创建时间',
    width: 180,
    align: 'center',
    render: (row) => {
      if (!row.createOn) return '-'
      const date = new Date(row.createOn)
      return date
        .toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit',
          second: '2-digit',
          hour12: false,
        })
        .replace(/\//g, '-')
    },
  },
  {
    prop: 'orderNum',
    label: '排序',
    width: 120,
    align: 'center',
    render: (row) =>
      h(
        'div',
        {
          style: {
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            gap: '4px',
          },
        },
        [
          h(
            ElButton,
            {
              size: 'small',
              type: 'primary',
              link: true,
              disabled: row.upDisabled,
              onClick: (e) => {
                e.stopPropagation()
                handlers.onMoveUp?.(row)
              },
            },
            () => h(ElIcon, null, () => h(ArrowUp)),
          ),
          h(
            'span',
            {
              style: {
                margin: '0 8px',
                minWidth: '40px',
                textAlign: 'center',
              },
            },
            row.orderNum,
          ),
          h(
            ElButton,
            {
              size: 'small',
              type: 'primary',
              link: true,
              onClick: (e) => {
                e.stopPropagation()
                handlers.onMoveDown?.(row)
              },
            },
            () => h(ElIcon, null, () => h(ArrowDown)),
          ),
        ],
      ),
  },
  {
    prop: 'tags',
    label: '标签',
    width: 180,
    render: (row) => (row.tags && row.tags.length ? row.tags.map((t) => t.name).join(', ') : '-'),
  },
]

/**
 * 获取搜索表单默认值
 */
export const getSearchFormDefaultValues = () => {
  return searchConfig.reduce((acc, item) => {
    acc[item.field] = item.defaultValue
    return acc
  }, {})
}
